import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); //设置是否有右上角转圈

const messages = {
	401: "未授权",
	403: "禁止访问",
	404: "资源找不到",
	500: "服务器错误"
};

const request = axios.create({
	baseURL: "/mock",
	headers: {},
	timeout: 1000
});

request.interceptors.request.use((config) => {
	NProgress.start();
	return config;
});

request.interceptors.response.use(
	(response) => {
		NProgress.done();
		if (response.data.code === 200) {
			return response.data.data;
		} else {
			return Promise.reject(response.data.message || "未知错误，请练习管理员");
		}
	},
	(e) => {
		NProgress.done();
		let message = "未知错误，请联系管理员";
		if (e.response) {
			message = messages[response.data.code];
		} else if (e.message.indexOf("timeout") > -1) {
			message = "请求超时，请检查网络";
		} else if (e.message.indexOf("Network") > -1) {
			message = "网络故障，请检查网络";
		}
		return Promise.reject(message);
	}
);

export default request;
